package com.lancoo.cvas.schedues;

import cn.hutool.core.collection.CollUtil;
import com.lancoo.cvas.entity.TaskInfo;
import com.lancoo.cvas.pojo.common.Deleted;
import com.lancoo.cvas.pojo.vo.CurrentTermInfo;
import com.lancoo.cvas.service.TaskInfoService;
import com.lancoo.cvas.service.YunService;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Component
@Slf4j
@EnableAsync(proxyTargetClass = true)
public class InitTerm {

    @Resource
    private YunService yunService;

    @Resource
    private TaskInfoService taskInfoService;


    @Scheduled(cron = "0 0 1 * * ?")
    public void initTeacher() {
        List<TaskInfo> taskInfoList = taskInfoService.lambdaQuery().eq(TaskInfo::getDeleted, Deleted.NOT.getCode()).list();
        if (CollUtil.isNotEmpty(taskInfoList)) {
            List<String> collect = taskInfoList.stream().map(TaskInfo::getSchoolId).distinct().collect(Collectors.toList());
            List<CurrentTermInfo> currentTermInfos = new ArrayList<>();
            collect.forEach(o -> {
                CurrentTermInfo currentTermInfo = yunService.GetCurrentTermInfo(o);
                currentTermInfos.add(currentTermInfo);
            });
            Map<String, List<TaskInfo>> collect1 = taskInfoList.stream().collect(Collectors.groupingBy(TaskInfo::getSchoolId));
            collect1.forEach((key,value)->{
                CurrentTermInfo currentTermInfo = currentTermInfos.stream().filter(p -> p.getSchoolID().equals(key)).findFirst().orElse(null);
                for (TaskInfo taskInfo : value) {
                    if (taskInfo.getTerm().equals(currentTermInfo.getTerm())) {
                        taskInfo.setOpenType(0);
                    }
                }
            });
            taskInfoService.saveOrUpdateBatch(taskInfoList);
            log.info("学期更新成功");
        } else {
            log.error("没有开课计划，不需要初始化学期信息");
        }
    }


}
